﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Reflection;
using UtfprLibrary.Communication.Contracts;
using UtfprLibrary.Exceptions;

namespace UtfprLibrary.Communication.Behaviors {
    /// <summary>
    /// TODO
    /// </summary>
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Publishing : IPublishing {
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="message"></param>
        /// <param name="subject"></param>
        public void Publish(Message message, string subject) {
            try {
                List<IPublishing> subscribers = Filter.GetSubscribers(subject);
                if (subscribers == null) {
                    return;
                }

                Type type = typeof(IPublishing);
                MethodInfo publishMethodInfo = type.GetMethod("Publish");

                foreach (IPublishing subscriber in subscribers) {
                    try {
                        publishMethodInfo.Invoke(subscriber, new object[] { message, subject });
                    } catch {
                        throw;
                    }
                }
            } catch (Exception ex) {
                throw new UtfprCommunicationException(Properties.Resources.Communication_Publishing_ExMsg_Publish, ex);
            }
        }
    }
}